package com.ruoyi.custservice.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.mapper.LoanDeferredOrderMapper;
import com.ruoyi.bizsys.mapper.ProductDeferredInfoMapper;
import com.ruoyi.bizsys.mapper.ProductRelationDeferredMapper;
import com.ruoyi.bizsys.service.ICustomerInfoService;
import com.ruoyi.bizsys.service.ILoanIouService;
import com.ruoyi.bizsys.service.IProductDeferredInfoService;
import com.ruoyi.bizsys.vo.LoanDeferredOrderOfferVo;
import com.ruoyi.bizsys.vo.LoanDeferredOrderVo;
import com.ruoyi.bizsys.vo.MonnifyReservedAccount;
import com.ruoyi.collection.domain.ProductDeferredVO;
import com.ruoyi.collection.service.IDeferredService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DesensitizeUtils;
import com.ruoyi.common.utils.Func;
import com.ruoyi.custservice.domain.*;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.custservice.mapper.CustomerMapper;
import com.ruoyi.custservice.service.CustomerService;

@Service
@Slf4j
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    ISysConfigService sysConfigService;

    @Autowired
    IProductDeferredInfoService productDeferredInfoService;

    @Autowired
    ProductRelationDeferredMapper productRelationDeferredMapper;

    @Autowired
    ILoanIouService loanIouService;

    @Autowired
    ProductDeferredInfoMapper productDeferredInfoMapper;

    @Autowired
    ICustomerInfoService customerInfoService;

    @Autowired
    private IDeferredService deferredService;

    @Autowired
    LoanDeferredOrderMapper loanDeferredOrderMapper;


    @Override
    public List<CustomerRsp> selectCustomerList(CustomerRsp customer) {
        return customerMapper.selectCustomerList(customer);
    }

    @Override
    public CustomerRsp selectCustomerByCustNo(String custNo) {
        CustomerRsp customerRsp = new CustomerRsp();
        // 查询custom_info表中的相关字段
        CustomerRsp customerInfo = customerMapper.selectCustomerInfoByCustNo(custNo);
        if (null == customerInfo) {
            return customerRsp;
        }
        customerRsp.setEmail(customerInfo.getEmail());
        customerRsp.setCustNo(customerInfo.getCustNo());
        customerRsp.setLevel(sysConfigService.selectConfigKey(customerInfo.getLevel()));
        String userId = customerInfo.getUserId();
        // 查询出app_user表中的相关字段
        CustomerRsp appUserInfo = customerMapper.findAppUserInfo(userId);
        String customTag =  customerMapper.findTag(userId);
        if (null != appUserInfo) {
            customerRsp.setRecommendCode(appUserInfo.getRecommendCode());
            customerRsp.setRegistrationMobile(appUserInfo.getRegistrationMobile());
            customerRsp.setEncryptMobile(appUserInfo.getEncryptMobile());
            customerRsp.setRegistrationTime(appUserInfo.getRegistrationTime());
            customerRsp.setState(customTag);
            /*String loanState = customerMapper.selectLoanState(custNo);
            String applyState = customerMapper.selectApplyState(custNo);
            if ("1".equals(appUserInfo.getState())) {
                customerRsp.setState("Blocked");
            } else if ("0".equals(loanState)) {
                customerRsp.setState("Delay");
            } else if ("0".equals(applyState)) {
                customerRsp.setState("Rejested");
            } else {
                customerRsp.setState("Potre");
            }*/
        }

        // 查询real_name_auth表中的相关字段
        CustomerRsp realNameInfo = customerMapper.findRealNameInfo(custNo);
        if (null != realNameInfo) {
            customerRsp.setClientName(realNameInfo.getClientName());
            customerRsp.setBirthDate(realNameInfo.getBirthDate());
            customerRsp.setMobile(realNameInfo.getMobile());
            customerRsp.setBvn(realNameInfo.getBvn());
            customerRsp.setAge(realNameInfo.getAge());
            customerRsp.setGender(realNameInfo.getGender());
        }

        // 查询登陆版本号信息
        String appVersion = customerMapper.findAppVersion(userId);
        customerRsp.setVersion(appVersion);
        // 查询credit_account表中的相关字段
        CustomerRsp creditAccountInfo = customerMapper.findCreditAccountInfo(custNo);
        if (null != creditAccountInfo) {
            customerRsp.setTotalLimit(creditAccountInfo.getTotalLimit().setScale(2, BigDecimal.ROUND_UP));
            customerRsp.setAvailableLimit(creditAccountInfo.getAvailableLimit().setScale(2, BigDecimal.ROUND_UP));
            customerRsp.setBorrowed(creditAccountInfo.getBorrowed().setScale(2, BigDecimal.ROUND_UP));
            customerRsp.setOverflowAmount(creditAccountInfo.getOverflowAmount().setScale(2, BigDecimal.ROUND_UP));
            customerRsp.setFrozenOverflowAmount(creditAccountInfo.getFrozenOverflowAmount().setScale(2, BigDecimal.ROUND_UP));
        }

        // 查询利息 屏蔽
       /* BigDecimal interest = customerMapper.findInterest(custNo);
        customerRsp.setInterest(interest);*/
        // 查询最近一条授信申请表的申请状态
        String applyStatus = customerMapper.findApplyStatus(custNo);
        customerRsp.setApplyStatus(applyStatus);
        // 查询最近一条的借款状态和创建时间
        CustomerRsp loanStatusInfo = customerMapper.findLoanStatus(custNo);
        if (null != loanStatusInfo) {
            customerRsp.setLoanStatus(loanStatusInfo.getLoanStatus());
            customerRsp.setLoanOrderCreatetime(loanStatusInfo.getLoanOrderCreatetime());
        }


        return customerRsp;
    }

    /**
     * 查询借款申请
     *
     * @param id 借款申请ID
     * @return 借款申请
     */
    @Override
    public LoanOrderVO selectLoanOrderInfo(Long id) {
        return customerMapper.selectLoanOrderInfo(id);
    }

    /**
     * 查询借款申请列表
     *
     * @param loanOrder 借款申请
     * @return 借款申请集合
     */
    @Override
    public List<LoanOrderVO> selectLoanOrderList(LoanOrderVO loanOrder) {
        return customerMapper.selectLoanOrderList(loanOrder);
    }

    /**
     * 查询出现在和之前的授信等级
     *
     * @param custNo
     * @return
     */
    @Override
    public ArrayList<RuleOut> selectNowAndBeforeCreditRating(String custNo) {
        return customerMapper.selectNowAndBeforeCreditRating(custNo);
    }

    /**
     * 查询银行卡号和银行名称
     */
    @Override
    public List<BankRsp> findBankByCustNo(String custNo) {
        return customerMapper.findBankByCustNo(custNo);
    }

    /**
     * 查询出用户绑卡记录
     *
     * @param custNo
     * @return
     */
    @Override
    public List<BindBankLogRsp> findBindBankLogByCustNo(String custNo) {
        return customerMapper.findBindBankLogByCustNo(custNo);
    }

    /**
     * 根据借据流水号查询出所有的还款记录
     *
     * @param loanSerialNo
     * @return
     */
    @Override
    public List<RepaymentOrderRsp> findRepaymentOrderByLoanSerialNo(String loanSerialNo) {
        return customerMapper.findRepaymentOrderByLoanSerialNo(loanSerialNo);
    }

    // 根据用户号查询五个详情是否有数据

    @Override
    public IsExistRsp selectIsExist(String custNo) {
        return customerMapper.selectIsExist(custNo);
    }

    // 根据订单流水号查询出来还款的总金额
    @Override
    public BigDecimal findAllRepaid(String loanSerialNo) {
        BigDecimal allRepaid = customerMapper.findAllRepaid(loanSerialNo);
        return allRepaid;
    }

    // 查询出来不脱敏的手机号
    @Override
    public String selectRegisterByCustNo(String custNo) {
        return customerMapper.selectRegisterByCustNo(custNo);
    }

    // 查询出来邀请码的状态
    @Override
    public String selectInviteStatus(String recommendCode) {
        return customerMapper.selectInviteStatus(recommendCode);
    }

    // 查询出参数accountNumber 和 bvn
    @Override
    public BankRsp selectAccountNumberAndBank(Integer id) {
        return customerMapper.selectParam(id);
    }

    /**
     * 根据用户customer_no查询出来所有的实名认证信息
     *
     * @param custNo
     * @return
     */
    @Override
    public List<RealNameAuthLogRsp> findListByCustNo(String custNo) {
        List<RealNameAuthLogRsp> realNameAuthLogs = customerMapper.findListByCustNo(custNo);
        realNameAuthLogs.stream().forEach(e->{
            e.setPhoneNumber(DesensitizeUtils.right(e.getPhoneNumber(),4));
        });
        return realNameAuthLogs;
    }

    /**
     * 根据cust_no查询出来授信申请记录
     */
    @Override
    public List<CreditApplyRsp> findCreditListByCustNo(String custNo) {
        // 查询出授信记录
        List<CreditApplyRsp> listByCustNo = customerMapper.findCreditListByCustNo(custNo);
        return listByCustNo;
    }

    // 查询实名认证表里是否有数据
    @Override
    public int selectRealNameAuth(String custNo) {
        return customerMapper.selectRealNameAuth(custNo);
    }

    @Override
    public CustomerRsp findClientNameByCustNo(String custNo) {
        CustomerRsp realNameInfo = customerMapper.findRealNameInfo(custNo);
        return realNameInfo;
    }

    /**
     * 用户延期offer
     * @param loanDeferredOrder
     * @return
     */
    @Override
    public LoanDeferredOrderOfferVo selectdeferredInfo(LoanDeferredOrder loanDeferredOrder) {
        LoanDeferredOrderOfferVo loanDeferredOrderOfferVo = new LoanDeferredOrderOfferVo();
        //查询用户是否拥有延期权益
        List<ProductDeferredVO> deferredList = deferredService.getDeferredByLoanNo(loanDeferredOrder.getLoanSerialNo());
        if (deferredList.size() > 0) {
            deferredList.forEach(e ->{
               if(e.getNumDeferredDay() == 7){
                   loanDeferredOrderOfferVo.setSevenMinRepay(e.getMinRepay());
                   loanDeferredOrderOfferVo.setSevenRepaymentDate(e.getDeferredRepayDate());
                   loanDeferredOrderOfferVo.setSevenExtensionDays(e.getNumDeferredDay());
               }else if(e.getNumDeferredDay() == 14){
                   loanDeferredOrderOfferVo.setFourteenMinRepay(e.getMinRepay());
                   loanDeferredOrderOfferVo.setFourteenRepaymentDate(e.getDeferredRepayDate());
                   loanDeferredOrderOfferVo.setFourteenExtensionDays(e.getNumDeferredDay());
               }
            });
            return loanDeferredOrderOfferVo;
        }
        return loanDeferredOrderOfferVo;
    }


    /**
     * 用户延期订单
     * @param loanDeferredOrder
     * @return
     */
    @Override
    public List<LoanDeferredOrderVo> selectLoanDeferredOrderFunList(LoanDeferredOrder loanDeferredOrder) {
        List<LoanDeferredOrderVo> loanDeferredOrderVos = new ArrayList<>();
        DecimalFormat df2 = new DecimalFormat("#,###");//千分位格式化
        List<LoanDeferredOrderVo> loanDeferredOrderVoList = loanDeferredOrderMapper.selectLoanDeferredOrderFunList(loanDeferredOrder);
        loanDeferredOrderVoList.forEach(e -> {
            LoanDeferredOrderVo loanDeferredOrderVo = new LoanDeferredOrderVo();
            loanDeferredOrderVo.setMinRepay("₦ " + new BigDecimal(e.getMinRepay()).setScale(2, BigDecimal.ROUND_UP));
            loanDeferredOrderVo.setNumDeferredDay(e.getNumDeferredDay() + " days");
            loanDeferredOrderVo.setCreateTime(e.getCreateTime());
            loanDeferredOrderVo.setNewRepaymentDate(e.getNewRepaymentDate());
            loanDeferredOrderVo.setStatus(e.getStatus());
            loanDeferredOrderVos.add(loanDeferredOrderVo);
        });
        return loanDeferredOrderVos;
    }

    @Override
    public MonnifyReservedAccount getVaReservedAccount(String custNo) {
        ExtPaystackReservedAccounts extPaystackReservedAccounts = customerMapper.getVaReservedAccount(custNo);
        if (null == extPaystackReservedAccounts) {
            return null;
        }
        MonnifyReservedAccount monnifyReservedAccount = new MonnifyReservedAccount();
        monnifyReservedAccount.setAccountNumber(extPaystackReservedAccounts.getAccountsAccountNumber());
        monnifyReservedAccount.setAccountName(extPaystackReservedAccounts.getAccountsAccountName());
        monnifyReservedAccount.setBankName(extPaystackReservedAccounts.getAccountsBankName());
        monnifyReservedAccount.setBankCode(extPaystackReservedAccounts.getAccountsBankCode());
        return monnifyReservedAccount;
    }

}
